//
//  newOperate.cpp
//  learnC++
//
//  Created by apple on 2018/5/29.
//  Copyright © 2018年 yunfan.com. All rights reserved.
//

#include "newOperate.hpp"

using namespace std;

static void doSomething()
{
    int *ptr = new int;
    //丢失了指向内存的指针导致内存泄露
}

static void test_leak(){
    int value = 5;
    int *ptr = new int; // allocate memory
    
    delete ptr;//指向其他内存之前，需释放之前的
    
    ptr = &value;
    
    //=======分割线
    //双重分配导致泄露
    int *ptr2 = new int;
    ptr2 = new int;
    
}

void test_new(){
    
    //动态内存分配  new = malloc()  delete = free()
    int *ptr1 = new int(5);
    int *ptr2 = new int{6};
    
    cout << *ptr1 << "=ptr1\n";
    cout << *ptr2 << "=ptr2\n";
    
    *ptr1 = 3;
    *ptr2 = 0;
    
    cout << *ptr1 << "=ptr1\n";
    cout << *ptr2 << "=ptr2\n";
    
    delete ptr1;
    delete ptr2;
    ptr1 = ptr2 = nullptr;
    
    int *ptr3 = nullptr;
    delete ptr3;
    
    error_solve();
    test_leak();
}

void error_solve(){
//    std::nothrow表示分配内存失败返回空指针
    int *value = new (std::nothrow) int(5);
    
    if (!value) {
        printf("分配内存失败");
        return;
    }
    
    cout<< *value << "=value\n";
}


